import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout } from '@/api/user'

// 管理端缓存key
const TOKEN_KEY = 'admin_token'
const USER_INFO_KEY = 'admin_user_info'
const TOKEN_EXPIRE_KEY = 'admin_token_expire'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem(TOKEN_KEY) || '')
  const userInfo = ref(JSON.parse(localStorage.getItem(USER_INFO_KEY) || 'null'))

  // 计算属性：判断是否是管理员
  const isAdmin = computed(() => userInfo.value?.roleId === 1)
  // 获取用户角色ID
  const roleId = computed(() => userInfo.value?.roleId || 0)

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    if (info) {
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
    } else {
      localStorage.removeItem(USER_INFO_KEY)
    }
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem(TOKEN_KEY, newToken)
      // 设置token过期时间为24小时
      const expireTime = new Date().getTime() + 24 * 60 * 60 * 1000
      localStorage.setItem(TOKEN_EXPIRE_KEY, expireTime.toString())
    } else {
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(TOKEN_EXPIRE_KEY)
    }
  }

  // 检查token是否过期
  const checkTokenExpire = () => {
    const expireTime = localStorage.getItem(TOKEN_EXPIRE_KEY)
    if (!expireTime) return false
    
    const now = new Date().getTime()
    if (now > Number(expireTime)) {
      // token已过期，清除用户信息
      setToken('')
      setUserInfo(null)
      return false
    }
    return true
  }

  // 登录方法
  const userLogin = async (loginData) => {
    try {
      const res = await login(loginData)
      if (res.code === 200 && res.data) {
        setToken(res.data.token)
        setUserInfo(res.data.userInfo)
        return res.data
      }
      throw new Error(res.message || '登录失败')
    } catch (error) {
      throw error
    }
  }

  // 登出方法
  const userLogout = async () => {
    // 先清除本地数据
    setToken('')
    setUserInfo(null)
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
    
    // 尝试调用登出接口
    try {
      await logout()
    } catch (error) {
      console.warn('登出接口调用失败:', error)
    }
  }

  return {
    token,
    userInfo,
    isAdmin,
    roleId,
    setUserInfo,
    setToken,
    userLogin,
    userLogout,
    checkTokenExpire
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userInfo']
      }
    ]
  }
})
